<script setup lang="ts">
import { fullUrl, previewImg } from '@/utils/common'
import { getDeliveryCompanyApi } from '@/api/delivery'
import { getOrderRefundDetailApi, postOrderRefundReturnApi } from '@/api/order'
import type { deliveryCompanyItem } from '@/types/delivery'
import type { orderRefundDetailResult } from '@/types/order'
import { onLoad } from '@dcloudio/uni-app'
import { computed } from 'vue'
import { ref } from 'vue'
import { pageUrl } from '@/utils/constants'

const props = defineProps<{
  data: string
  id: number
}>()

const orderData = ref<orderRefundDetailResult>()

const getOrderData = async () => {
  const res = await getOrderRefundDetailApi({ id: props.id })
  orderData.value = res.result
}

// 审核状态
enum auditStatusEnum {
  wait_audit = 1,
  agree = 2,
  refuse = 3,
  cancel = 4,
}

// 显示协商历史
const showHistory = computed(() => {
  return orderData.value?.audit_status == auditStatusEnum.refuse
})
// 显示退货地址
const showDelivery = computed(() => {
  return orderData.value?.audit_status == auditStatusEnum.agree && orderData.value.refund_address
})
// 复制地址
const copyAddress = () => {
  const fullAddress = `Recipient: ${orderData.value?.refund_address.name} Phone: ${orderData.value?.refund_address.phone} Address: ${orderData.value?.refund_address.full_address}`

  uni.setClipboardData({
    data: fullAddress,
    success: () => {
      uni.showToast({
        title: 'Copied successfully',
        icon: 'none',
      })
    },
  })
}

const deliveryCompanyOptions = ref<deliveryCompanyItem[]>([])
const companyIndex = ref(0)

const getDeliveryCompanyData = async () => {
  // 有物流信息时不请求
  if (deliverForm.value.delivery_company && deliverForm.value.delivery_no) return

  const res = await getDeliveryCompanyApi()
  res.result.unshift({ id: 0, name: 'Please select shipping company', code: '' })
  deliveryCompanyOptions.value = res.result
}

const deliverForm = ref({
  delivery_company_id: 0,
  delivery_company: '',
  delivery_no: '',
})
const deliverFormRules = ref({
  delivery_no: {
    rules: [{ required: true, errorMessage: 'Please enter tracking number' }],
  },
})

const onChnageCompanyIndex = (event: UniHelper.SelectorPickerOnChangeEvent) => {
  companyIndex.value = event.detail.value
  const deliveryCompany = deliveryCompanyOptions.value.find((item) => item.id == companyIndex.value)

  deliverForm.value.delivery_company_id = deliveryCompany!.id
  deliverForm.value.delivery_company = deliveryCompany!.name
}

const formRef = ref()
const onSubmit = async () => {
  if (!deliverForm.value.delivery_company_id) {
    uni.showToast({
      title: 'Please select shipping company',
      icon: 'none',
    })
    return
  }
  await formRef.value.validate()
  const params = {
    id: props.id,
    ...deliverForm.value,
  }
  const res = await postOrderRefundReturnApi(params)
  uni.showToast({
    title: res.msg,
    icon: 'none',
  })
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

const refundTypeText = computed(() => {
  switch (orderData.value?.refund_type) {
    case 1:
      return 'Return & Refund'
    case 2:
      return 'Exchange'
    default:
      return ''
  }
})

onLoad(async () => {
  await getOrderData()
  await getDeliveryCompanyData()
})
</script>

<template>
  <view class="detail" v-if="orderData">
    <view class="status">
      <image class="image" src="/static/images/bg.png" />
      <text>{{ orderData.status_text }}</text>
    </view>
    <view class="order">
      <view class="card">
        <text class="title">Return Items</text>
        <navigator
          class="goods"
          :url="`${pageUrl['goods-detail']}?id=${orderData.detail.goods_id}`"
          hover-class="none"
        >
          <image class="cover" :src="fullUrl(orderData.detail.image)"></image>
          <view class="meta">
            <view class="name ellipsis">{{ orderData.detail.goods_name }}</view>
            <!-- <view class="meta-spec">{{ orderData.detail.spec }}</view> -->
            <view class="meta-spec" v-if="orderData.detail.spec">
              <view class="color">
                <text>Color：</text>
                <image class="color" :src="fullUrl(orderData.detail.spec.split('，')[0])" alt="" />
              </view>
              <view class="size">
                <text>Size：</text>{{ orderData.detail.spec.split('，')[1] }}
              </view>
            </view>
            <view class="meta-quantity">x{{ orderData!.refund_num }}</view>
          </view>
        </navigator>
        <view class="detail">
          <view class="detail-item" v-if="parseFloat(orderData.apply_money) > 0">
            <text>Requested Amount</text>
            <text class="amount">${{ orderData.apply_money }}</text>
          </view>
          <view class="detail-item" v-if="parseFloat(orderData.refund_money) > 0">
            <text>Refund Amount</text>
            <text class="amount">${{ orderData.refund_money }}</text>
          </view>
          <view class="detail-item" v-if="parseFloat(orderData.refund_freight) > 0">
            <text>Shipping Refund</text>
            <text>${{ orderData.refund_freight }}</text>
          </view>
          <view class="detail-item">
            <text>Request Time</text>
            <text>{{ orderData.create_time }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="block" v-if="showHistory">
      <view class="history">
        <view class="header">
          <text class="title">Negotiation History</text>
        </view>
        <view class="history-item">
          <text>Return Type: {{ refundTypeText }}</text>
        </view>
        <view class="history-item">
          <text>Reason: {{ orderData.remark }}</text>
        </view>
        <view class="history-item" v-if="orderData.remark_images">
          <text>Evidence:</text>
          <view class="images-container">
            <image
              v-for="(item, index) in orderData.remark_images"
              :key="index"
              :src="item"
              mode="aspectFit"
              @tap="previewImg(item, orderData!.remark_images)"
            />
          </view>
        </view>
        <view class="history-item" v-if="orderData.refuse_reason">
          <text>Seller's Response: {{ orderData.refuse_reason }}</text>
        </view>
      </view>
    </view>

    <view class="block" v-if="showDelivery">
      <view class="address">
        <view class="header">
          <text class="title">Return Address</text>
          <button class="copy-button" @tap="copyAddress">Copy</button>
        </view>
        <view>
          <text>Recipient: {{ orderData.refund_address.name }}</text>
        </view>
        <view>
          <text>Phone: {{ orderData.refund_address.phone }}</text>
        </view>
        <view>
          <text>Address: {{ orderData.refund_address.full_address }}</text>
        </view>
        <view class="remark">
          <text>Please don't use standard mail or cash on delivery without prior agreement with the seller</text>
        </view>
      </view>
    </view>

    <view class="block" v-if="showDelivery">
      <view class="delivery">
        <view class="header">
          <text class="title">Return Shipping</text>
        </view>
        <uni-list v-if="orderData.user_ship_delivery">
          <uni-list-item
            title="Shipping Company"
            :rightText="orderData.user_ship_delivery.delivery_company"
          >
          </uni-list-item>
          <uni-list-item title="Tracking Number" :rightText="orderData.user_ship_delivery.delivery_no">
          </uni-list-item>
        </uni-list>
        <view v-else>
          <uni-forms
            ref="formRef"
            label-width="100"
            validate-trigger="blur"
            :rules="deliverFormRules"
            :model="deliverForm"
          >
            <uni-forms-item required label="Shipping Company" name="delivery_company">
              <view style="display: flex; align-items: center; height: 35px">
                <picker
                  mode="selector"
                  :range="deliveryCompanyOptions"
                  range-key="name"
                  :value="companyIndex"
                  @change="onChnageCompanyIndex"
                >
                  <text>{{ deliveryCompanyOptions[companyIndex]?.name }}</text>
                </picker>
              </view>
            </uni-forms-item>
            <uni-forms-item required label="Tracking Number" name="delivery_no">
              <uni-easyinput
                v-model="deliverForm.delivery_no"
                placeholder="Please enter tracking number"
                :disabled="Boolean(orderData.user_ship_status)"
              />
            </uni-forms-item>
          </uni-forms>
          <button class="sub-button" @tap="onSubmit" v-if="!Boolean(orderData.user_ship_status)">
            Submit Shipping Info
          </button>
        </view>
      </view>
    </view>

    <view class="block" v-if="orderData.exchange_delivery">
      <view class="delivery">
        <view class="header">
          <text class="title">Exchange Shipping</text>
        </view>
        <uni-list>
          <uni-list-item title="Shipping Company" :rightText="orderData.exchange_delivery.delivery_company">
          </uni-list-item>
          <uni-list-item title="Tracking Number" :rightText="orderData.exchange_delivery.delivery_no">
          </uni-list-item>
        </uni-list>
      </view>
    </view>

    <view :style="{ paddingBottom: '100rpx' }"></view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f6f6f6;
}

.status {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 150rpx;

  /* 图片样式 */
  .image {
    width: 100%;
    height: 150rpx;
    position: absolute;
    top: 0;
    left: 0;
  }

  /* 文本样式 */
  text {
    z-index: 1;
    font-size: 36rpx;
    color: #fff;
  }
}

.order {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;

  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .text {
      color: red;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    padding-top: 20rpx;
    padding-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      &-spec {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
        max-width: 90%;
      }

      &-quantity {
        position: absolute;
        right: 20px;
        font-size: 24rpx;
        color: #9e9c9c;
      }
    }

    .meta-spec{
      background: transparent;
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #888;
      span{
        font-size: 24rpx;
        color: #888;
      }
      .color{
        margin-right: 10rpx;
        image{
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          border: 1px solid #e3e3e3;
        }
      }
    }

    .name {
      font-size: 26rpx;
      color: #444;
      max-width: 90%;
    }
  }

  .detail {
    display: flex;
    flex-direction: column;
    color: #999;
    font-size: 28rpx;
  }

  .detail-item {
    display: flex;
    justify-content: space-between;
    padding: 5rpx;
  }

  .amount {
    color: red;
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .pay-time {
      font-size: 24rpx;
      color: #999;
      margin-right: 20rpx;
    }

    .countdown {
      font-size: 24rpx;
      color: #999;
      margin-left: auto;
      display: flex;
    }

    .button {
      width: 130rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #ff5f3c;
      border-color: #ff5f3c;
    }

    .primary {
      color: #fff;
      background-color: #ff5f3c;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}

.block {
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  margin: 20rpx 20rpx 0;
  border-radius: 10rpx;
  background-color: #fff;
}

.address view {
  margin-bottom: 20rpx;
  font-size: 24rpx;
}

.history view {
  margin-bottom: 20rpx;
}

.images-container {
  display: flex;

  image {
    width: 150rpx;
    height: 120rpx;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
}

.title {
  font-size: 35rpx;
}

.copy-button {
  display: flex;
  height: 50rpx;
  font-size: 24rpx;
  margin-right: initial;
  align-items: center;
}

.remark {
  padding: 10rpx 0 10rpx 0;
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
}

.sub-button {
  background-color: #ff5f3c;
  color: white;
  border-radius: 20rpx;
  text-align: center;
  cursor: pointer;
  margin: 20rpx;
}
</style>
